<?php

namespace app\admin\model;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\SoftDeletes;
use support\Model;
use support\Redis;

/**
 * bots 机器人
 * @property integer $id (主键)
 * @property string $name 机器人名
 * @property string $token 机器人token
 * @property string $avatar 机器人头像
 * @property integer $bot_id 所属机器人
 * @property string $backup_user_id 备份人的chat_id或username
 * @property bool $enable 是否启用
 * @property mixed $created_at 创建时间
 * @property mixed $updated_at 修改时间
 * @property string $deleted_at 删除时间
 */
class Bot extends Model
{
    use SoftDeletes;
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'bots';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';
    
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at'    =>  'datetime:Y-m-d H:i:s',
        'deleted_at'    =>  'datetime:Y-m-d H:i:s',
        'enable'    =>  'boolean'
    ];

    protected $appends = ['hook_loading'];

    /**
     * 关联备份机器人
     */
    public function backups(){
        return $this->hasMany(self::class, 'bot_id', 'id');
    }

    /**
     * 关联主机器人
     */
    public function master(){
        return $this->belongsTo(self::class, 'bot_id', 'id');
    }

    /**
     * 关联机器人命令
     */
    public function commands(){
        return $this->hasMany(BotCommand::class, 'bot_id', 'id');
    }

    /**
     * 关联机器人文件前缀
     */
    public function filePerfixs(){
        return $this->hasMany(BotFilePerfix::class, 'bot_id', 'id');
    }

    /**
     * 
     */
    public function hookLoading() :Attribute{
        return new Attribute(function(){
            return Redis::get('bot_hook_loading:'.$this->id);
        });
    }
}
